<template>
  <div>
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="router.back()"
      :title="'搜索：“' + keyword + '”的结果'"
      placeholder
      fixed
    />
    <div class="content">
      <van-card
        @click="onProductClick(item.id)"
        v-for="item in SeachData"
        :key="item.id"
        :price="item.price"
        :desc="item.desc"
        :title="item.name"
        :thumb="item.coverImage"
      />
    </div>

    <!-- 分页器 -->
    <van-pagination
      v-if="paginationShow"
      v-model="currentPage"
      :total-items="total"
      :items-per-page="10"
      :show-page-size="2"
      :force-ellipses="true"
      id="Paging"
      @change="changePage($event)"
    />
  </div>
</template>

<script setup>
import { getProductNameSeachReq } from '@/api/Produc'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useRoute } from 'vue-router'
//搜索结果
let total = ref(0) //总商品数，用于分页
let route = useRoute()
let SeachData = ref([])
let paginationShow = ref(true) //控制分页器是否显示
let keyword = route.query.keyword
function getSeachData() {
  getProductNameSeachReq(keyword).then((res) => {
    SeachData.value = res.data.data
    total.value = res.data.total
    //判断数据若大于10分页器就出现
    if (total.value <= 5) {
      paginationShow.value = false
    }
    // console.log('搜索结果：', res.data)
  })
}
getSeachData()

//分页器
const currentPage = ref(1)
function changePage(page) {
  // console.log('页码:', page)
  getProductNameSeachReq(keyword, page).then((res) => {
    SeachData.value = res.data.data
    // console.log('分页', res.data)
  })
}
//点击商品
let router = useRouter()
function onProductClick(id) {
  // console.log(id, '点击了商品')
  router.push('/detail?id=' + id)
}
</script>

<style scoped>
.content {
  margin-bottom: 45px;
}
#Paging {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
}
</style>
